package com.bottle.listener;

import com.bottle.enity.SingleChatRecord;
import com.bottle.event.ChatRecordEvent;
import com.bottle.event.MessageEvent;
import com.bottle.event.OutInfoEvent;
import com.bottle.event.WSMessageEvent;
import com.bottle.mode.ReJson;
import com.bottle.service.ChatRecrdService;
import com.bottle.web.WebSocketServer;
import com.google.common.collect.Multimap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: chenyuncong
 * @Date: 2020/5/11 15:47
 * 事件监听
 */
@Component
@Slf4j
public class MessageListener  {

    @Autowired
    private Multimap<String, DeferredResult<Object>> multimap;

    @Autowired
    private ChatRecrdService chatRecrdService;

    @Autowired
    private ConcurrentHashMap<String,WebSocketServer> wsSessionMap;

    //异步处理数据
    @Async
    @EventListener
    public void onMessageEvent(MessageEvent messageEvent) {
        Collection<DeferredResult<Object>> deferredResults = null;
        for (String onLineUserId : messageEvent.getOnLineSet()) {
            deferredResults = multimap.get(onLineUserId);  //获取在线用户返回对象
            if (!deferredResults.isEmpty()) {
                for (DeferredResult<Object> deferredResult : deferredResults) {
                    //给对象返回值
                    if (deferredResult != null) {
                        deferredResult.setResult(new ReJson(200, messageEvent.getMessage(), "传输信息"));
                    }
                }
            }
        }
    }

    @Async
    @EventListener
    public void onWSMessageEvent(WSMessageEvent messageEvent) {
//        Collection<DeferredResult<Object>> deferredResults = null;
        for (String onLineUserId : messageEvent.getOnLineSet()) {
            if(wsSessionMap.containsKey(onLineUserId)){
                WebSocketServer ws = wsSessionMap.get(onLineUserId);
                if(ws==null){
                    return;
                }
                Session seesionClient=ws.getSession();
                if(seesionClient!=null){
                    try {
                        if(seesionClient.isOpen()){
                            synchronized (seesionClient){
                                seesionClient.getBasicRemote().sendText(messageEvent.getMessage());
                            }
                        }
                    } catch (IOException e) {
                        log.error("发送消息出错：{}", e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //websocket
//    @Async
//    @EventListener
//    public void onWsMessageEvent(MessageEvent messageEvent) {
//
//    }

    //聊天记录
    @Async
    @EventListener
    public void onChatRecrd(ChatRecordEvent chatRecordEvent){
        SingleChatRecord scr=new SingleChatRecord();
        scr.setContent(chatRecordEvent.getContent());
        scr.setCreateTime(chatRecordEvent.getCreateTime());
        scr.setSendTime(chatRecordEvent.getSendTime());
        scr.setUserId(chatRecordEvent.getUserId());
        scr.setEncryptionId(chatRecordEvent.getEncryptionId());
        chatRecrdService.saveSingleChatRecord(scr);
    }

    @Async
    @EventListener
    public void outInfo(OutInfoEvent outInfoEvent){
        log.info("异步打印信息[{}]",outInfoEvent.getMessage());
    }
}
